home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / text / faqs / unix-faq.shell.csh-whynot < prev    next >
Encoding:
Internet Message Format  |  1993-10-28  |  14.6 KB

  1. Subject: Csh Programming Considered Harmful 
  2. Newsgroups: comp.unix.shell,comp.unix.questions,comp.unix.programmer,news.answers
  3. From: Tom Christiansen <tchrist@cs.Colorado.EDU>
  4. Date: Wed, 27 Oct 1993 12:44:30 GMT
  5.  
  6. Archive-name: unix-faq/shell/csh-whynot
  7. Version: $Id: csh-faq,v 1.5 93/10/01 13:26:05 tchrist Exp Locker: tchrist $
  8.  
  9. The following periodic article answers in excruciating detail
  10. the frequently asked question "Why shouldn't I program in csh?".
  11. It is available for anon FTP from convex.com in /pub/csh.whynot .
  12.  
  13.  
  14.            *** CSH PROGRAMMING CONSIDERED HARMFUL ***
  15.  
  16.     Resolved: The csh is a tool utterly inadequate for programming, 
  17.           and its use for such purposes should be strictly banned!
  18.  
  19. I am continually shocked and dismayed to see people write test cases,
  20. install scripts, and other random hackery using the csh.  Lack of
  21. proficiency in the Bourne shell has been known to cause errors in /etc/rc
  22. and .cronrc files, which is a problem, because you *must* write these files
  23. in that language.
  24.  
  25. The csh is seductive because the conditionals are more C-like, so the path
  26. of least resistance is chosen and a csh script is written.  Sadly, this is
  27. a lost cause, and the programmer seldom even realizes it, even when they
  28. find that many simple things they wish to do range from cumbersome to
  29. impossible in the csh.
  30.  
  31.  
  32. 1. FILE DESCRIPTORS
  33.  
  34. The most common problem encountered in csh programming is that
  35. you can't do file-descriptor manipulation.  All you are able to 
  36. do is redirect stdin, or stdout, or dup stderr into stdout. 
  37. Bourne-compatible shells offer you an abundance of more exotic
  38. possibilities.    
  39.  
  40. 1a. Writing Files
  41.  
  42. In the Bourne shell, you can open or dup arbitrary file descriptors.
  43. For example, 
  44.  
  45.     exec 2>errs.out
  46.  
  47. means that from then on, stderr goes into errs file.
  48.  
  49. Or what if you just want to throw away stderr and leave stdout
  50. alone?    Pretty simple operation, eh?
  51.  
  52.     cmd 2>/dev/null
  53.  
  54. Works in the Bourne shell.  In the csh, you can only make a pitiful 
  55. attempt like this:
  56.  
  57.     (cmd > /dev/tty) >& /dev/null
  58.  
  59. But who said that stdout was my tty?  So it's wrong.  This simple
  60. operation *CANNOT BE DONE* in the csh.
  61.  
  62.  
  63. Along these same lines, you can't direct error messages in csh scripts
  64. out stderr as is considered proper.  In the Bourne shell, you might say:
  65.  
  66.     echo "$0: cannot find $file" 1>&2
  67.  
  68. but in the csh, you can't redirect stdout out stderr, so you end
  69. up doing something silly like this:
  70.  
  71.     sh -c 'echo "$0: cannot find $file" 1>&2'
  72.  
  73. 1b. Reading Files
  74.  
  75. In the csh, all you've got is $<, which reads a line from your tty.  What
  76. if you've redirected stdin?  Tough noogies, you still get your tty, which 
  77. you really can't redirect.  Now, the read statement 
  78. in the Bourne shell allows you to read from stdin, which catches
  79. redirection.  It also means that you can do things like this:
  80.  
  81.     exec 3<file1
  82.     exec 4<file2
  83.  
  84. Now you can read from fd 3 and get lines from file1, or from file2 through
  85. fd 4.   In modern, Bourne-like shells, this suffices: 
  86.  
  87.     read some_var 0<&3
  88.     read another_var 0<&4
  89.  
  90. Although in older ones where read only goes from 0, you trick it:
  91.  
  92.     exec 5<&0  # save old stdin
  93.     exec 0<&3; read some_var
  94.     exec 0<&4; read another_var
  95.     exec 0<&5  # restore it
  96.  
  97.  
  98. 1c. Closing FDs
  99.  
  100. In the Bourne shell, you can close file descriptors you don't
  101. want open, like 2>&-, which isn't the same as redirecting it
  102. to /dev/null.
  103.  
  104. 1d. More Elaborate Combinations
  105.  
  106. Maybe you want to pipe stderr to a command and leave stdout alone.
  107. Not too hard an idea, right?  You can't do this in the csh as I
  108. mentioned in 1a.  In a Bourne shell, you can do things like this:
  109.  
  110.     exec 3>&1; grep yyy xxx 2>&1 1>&3 3>&- | sed s/file/foobar/ 1>&2 3>&-
  111.     grep: xxx: No such foobar or directory
  112.  
  113. Normal output would be unaffected.  The closes there were in case
  114. something really cared about all its FDs.  We send stderr to sed,
  115. and then put it back out 2.
  116.  
  117. Consider the pipeline:
  118.  
  119.     A | B | C
  120.  
  121. You want to know the status of C, well, that's easy: it's in $?, or
  122. $status in csh.  But if you want it from A, you're out of luck -- if
  123. you're in the csh, that is.  In the Bourne shell, you can get it, although
  124. doing so is a bit tricky.  Here's something I had to do where I ran dd's
  125. stderr into a grep -v pipe to get rid of the records in/out noise, but had
  126. to return the dd's exit status, not the grep's:
  127.  
  128.     device=/dev/rmt8
  129.     dd_noise='^[0-9]+\+[0-9]+ records (in|out)$'
  130.     exec 3>&1
  131.     status=`((dd if=$device ibs=64k 2>&1 1>&3 3>&- 4>&-; echo $? >&4) |
  132.         egrep -v "$dd_noise" 1>&2 3>&- 4>&-) 4>&1`
  133.     exit $status;
  134.  
  135.  
  136. The csh has also been known to close all open file descriptors besides
  137. the ones it knows about, making it unsuitable for applications that 
  138. intend to inherit open file descriptors.
  139.  
  140.  
  141. 2. COMMAND ORTHOGONALITY
  142.  
  143. 2a. Built-ins
  144.  
  145. The csh is a horrid botch with its built-ins.  You can't put them
  146. together in many reasonable ways.   Even simple little things like this:    
  147.  
  148.         % time | echo
  149.  
  150. which while nonsensical, shouldn't give me this message:
  151.  
  152.         Reset tty pgrp from 9341 to 26678
  153.  
  154. Others are more fun:
  155.  
  156.         % sleep 1 | while
  157.         while: Too few arguments.
  158.         [5] 9402
  159.         % jobs
  160.         [5]     9402 Done                 sleep |
  161.  
  162.  
  163. Some can even hang your shell.  Try typing ^Z while you're sourcing 
  164. something, or redirecting a source command.  Just make sure you have
  165. another window handy.  Or try 
  166.  
  167.     % history | more
  168.  
  169. on some systems.
  170.  
  171. Aliases are not evaluated everywhere you would like them do be:
  172.  
  173.     % alias lu 'ls -u'
  174.     % lu
  175.     HISTORY  News     bin      fortran  lib      lyrics   misc     tex
  176.     Mail     TEX      dehnung  hpview   logs     mbox     netlib
  177.     % repeat 3 lu
  178.     lu: Command not found.
  179.     lu: Command not found.
  180.     lu: Command not found.
  181.  
  182.     % time lu
  183.     lu: Command not found.
  184.  
  185.  
  186. 2b. Flow control
  187.  
  188. You can't mix flow-control and commands, like this:
  189.     
  190.     who | while read line; do
  191.     echo "gotta $line"
  192.     done
  193.  
  194.  
  195. You can't combine multiline constructs in a csh using semicolons.
  196. There's no easy way to do this
  197.  
  198.     alias cmd 'if (foo) then bar; else snark; endif'
  199.  
  200.  
  201. You can't perform redirections with if statements that are
  202. evaluated solely for their exit status:
  203.  
  204.     if ( { grep vt100 /etc/termcap > /dev/null } ) echo ok
  205.  
  206. And even pipes don't work:
  207.  
  208.     if ( { grep vt100 /etc/termcap | sed 's/$/###' } ) echo ok
  209.  
  210. But these work just fine in the Bourne shell:
  211.  
  212.     if grep vt100 /etc/termcap > /dev/null ; then echo ok; fi   
  213.  
  214.     if grep vt100 /etc/termcap | sed 's/$/###/' ; then echo ok; fi
  215.  
  216.  
  217. Consider the following reasonable construct:
  218.  
  219.   if ( { command1 | command2 } ) then
  220.       ...
  221.   endif
  222.  
  223. The output of command1 won't go into the input of command2.  You will get
  224. the output of both commands on standard output.  No error is raised.  In
  225. the Bourne shell or its clones, you would say 
  226.  
  227.     if command1 | command2 ; then
  228.     ...
  229.     fi
  230.  
  231.  
  232. 2c. Stupid parsing bugs
  233.  
  234. Certain reasonable things just don't work, like this:
  235.  
  236.     % kill -1 `cat foo`
  237.     `cat foo`: Ambiguous.
  238.  
  239. But this is ok:
  240.  
  241.     % /bin/kill -1 `cat foo`
  242.  
  243. If you have a stopped job:
  244.  
  245.     [2]     Stopped              rlogin globhost
  246.  
  247. You should be able to kill it with 
  248.  
  249.     % kill %?glob
  250.     kill: No match
  251.  
  252. but
  253.  
  254.     % fg %?glob
  255.  
  256. works.
  257.  
  258. White space can matter:
  259.  
  260.     if(expr)
  261.  
  262. may fail on some versions of csh, while
  263.  
  264.     if (expr)
  265.  
  266. works!
  267.  
  268.  
  269.  
  270. 3. SIGNALS
  271.  
  272. In the csh, all you can do with signals is trap SIGINT.  In the Bourne
  273. shell, you can trap any signal, or the end-of-program exit.    For example,
  274. to blow away a tempfile on any of a variety of signals:
  275.  
  276.     $ trap 'rm -f /usr/adm/tmp/i$$ ;
  277.         echo "ERROR: abnormal exit";
  278.         exit' 1 2 3 15
  279.  
  280.     $ trap 'rm tmp.$$' 0   # on program exit
  281.  
  282.  
  283.  
  284. 4. QUOTING
  285.  
  286. You can't quote things reasonably in the csh:
  287.  
  288.     set foo = "Bill asked, \"How's tricks?\""
  289.  
  290. doesn't work.  This makes it really hard to construct strings with
  291. mixed quotes in them.  In the Bourne shell, this works just fine. 
  292. In fact, so does this:
  293.  
  294.      cd /mnt; /usr/ucb/finger -m -s `ls \`u\``
  295.  
  296. Dollar signs cannot be escaped in double quotes in the csh.  Ug.
  297.  
  298.     set foo = "this is a \$dollar quoted and this is $HOME not quoted" 
  299.     dollar: Undefined variable.
  300.  
  301. You have to use backslashes for newlines, and it's just darn hard to
  302. get them into strings sometimes.
  303.  
  304.     set foo = "this \
  305.     and that";
  306.     echo $foo
  307.     this  and that
  308.     echo "$foo"
  309.     Unmatched ".  
  310.  
  311. Say what?  You don't have these problems in the Bourne shell, where it's
  312. just fine to write things like this:
  313.  
  314.     echo     'This is 
  315.          some text that contains
  316.          several newlines.'
  317.  
  318.  
  319. As distributed, quoting history references is a challenge.  Consider:
  320.  
  321.     % mail adec23!alberta!pixel.Convex.COM!tchrist
  322.     alberta!pixel.Convex.COM!tchri: Event not found.
  323.  
  324.  
  325. 5. VARIABLE SYNTAX
  326.  
  327. There's this big difference between global (environment) and local
  328. (shell) variables.  In csh, you use a totally different syntax 
  329. to set one from the other.  
  330.  
  331. In the Bourne shell, this 
  332.     VAR=foo cmds args
  333.  is the same as
  334.     (export VAR; VAR=foo; cmd args)
  335. or csh's
  336.     (setenv VAR;  cmd args)
  337.  
  338. You can't use :t, :h, etc on envariables.  Watch:
  339.     echo Try testing with $SHELL:t
  340.  
  341. It's really nice to be able to say
  342.     
  343.     ${PAGER-more}
  344. or
  345.     FOO=${BAR:-${BAZ}}
  346.  
  347. to be able to run the user's PAGER if set, and more otherwise.
  348. You can't do this in the csh.  It takes more verbiage.
  349.  
  350. You can't get the process number of the last background command from the
  351. csh, something you might like to do if you're starting up several jobs in
  352. the background.  In the Bourne shell, the pid of the last command put in
  353. the background is available in $!.
  354.  
  355. The csh is also flaky about what it does when it imports an 
  356. environment variable into a local shell variable, as it does
  357. with HOME, USER, PATH, and TERM.  Consider this:
  358.  
  359.     % setenv TERM '`/bin/ls -l / > /dev/tty`'
  360.     % csh -f
  361.  
  362. And watch the fun!
  363.  
  364.  
  365. 6. EXPRESSION EVALUATION
  366.  
  367. Consider this statement in the csh:
  368.  
  369.  
  370.     if ($?MANPAGER) setenv PAGER $MANPAGER
  371.  
  372.  
  373. Despite your attempts to only set PAGER when you want
  374. to, the csh aborts:
  375.  
  376.     MANPAGER: Undefined variable.
  377.  
  378. That's because it parses the whole line anyway AND EVALUATES IT!
  379. You have to write this:
  380.  
  381.     if ($?MANPAGER) then
  382.     setenv PAGER $MANPAGER
  383.     endif
  384.  
  385. That's the same problem you have here:
  386.  
  387.     if ($?X && $X == 'foo') echo ok
  388.     X: Undefined variable
  389.  
  390. This forces you to write a couple nested if statements.  This is highly
  391. undesirable because it renders short-circuit booleans useless in
  392. situations like these.  If the csh were the really C-like, you would
  393. expect to be able to safely employ this kind of logic.  Consider the
  394. common C construct:
  395.  
  396.     if (p && p->member) 
  397.  
  398. Undefined variables are not fatal errors in the Bourne shell, so 
  399. this issue does not arise there.
  400.  
  401. While the csh does have built-in expression handling, it's not
  402. what you might think.  In fact, it's space sensitive.  This is an
  403. error
  404.  
  405.    @ a = 4/2
  406.  
  407. but this is ok
  408.  
  409.    @ a = 4 / 2
  410.  
  411.  
  412. The ad hoc parsing csh employs fouls you up in other places 
  413. as well.  Consider:
  414.  
  415.     % alias foo 'echo hi' ; foo
  416.     foo: Command not found.
  417.     % foo
  418.     hi
  419.  
  420.  
  421.  
  422. 7. ERROR HANDLING
  423.  
  424. Wouldn't it be nice to know you had an error in your script before
  425. you ran it?   That's what the -n flag is for: just check the syntax.
  426. This is especially good to make sure seldom taken segments of code
  427. code are correct.  Alas, the csh implementation of this doesn't work.
  428. Consider this statement:
  429.  
  430.     exit (i)
  431.  
  432. Of course, they really meant
  433.  
  434.     exit (1)
  435.  
  436. or just
  437.  
  438.     exit 1
  439.  
  440. Either shell will complain about this.  But if you hide this in an if
  441. clause, like so:
  442.  
  443.     #!/bin/csh -fn
  444.     if (1) then
  445.     exit (i)
  446.     endif
  447.  
  448. The csh tells you there's nothing wrong with this script.  The equivalent
  449. construct in the Bourne shell, on the other hand, tells you this:
  450.  
  451.  
  452.     #!/bin/sh -n
  453.     if (1) then
  454.     exit (i)
  455.     endif
  456.  
  457.     /tmp/x: syntax error at line 3: `(' unexpected
  458.  
  459.  
  460.  
  461. RANDOM BUGS
  462.  
  463. Here's one:
  464.  
  465.     fg %?string
  466.     ^Z
  467.     kill  %?string
  468.     No match.
  469.  
  470. Huh? Here's another
  471.  
  472.     !%s%x%s
  473.  
  474. Coredump, or garbage.
  475.  
  476. If you have an alias with backquotes, and use that in backquotes in 
  477. another one, you get a coredump.
  478.  
  479. Try this:
  480.     % repeat 3 echo "/vmu*"
  481.     /vmu*
  482.     /vmunix
  483.     /vmunix
  484. What???
  485.  
  486.  
  487. Here's another one:
  488.  
  489.     % mkdir tst
  490.     % cd tst
  491.     % touch '[foo]bar'
  492.     % foreach var ( * )
  493.     > echo "File named $var"
  494.     > end
  495.     foreach: No match.
  496.  
  497.  
  498. 8. SUMMARY
  499.  
  500.  
  501. While some vendors have fixed some of the csh's bugs (the tcsh also does
  502. much better here), many have added new ones.  Most of its problems can
  503. never be solved because they're not actually bugs per se, but rather the
  504. direct consequences of braindead design decisions.  It's inherently flawed.
  505.  
  506. Do yourself a favor, and if you *have* to write a shell script, do it in the 
  507. Bourne shell.  It's on every UNIX system out there.  However, behavior 
  508. can vary.
  509.  
  510. There are other possibilities.
  511.  
  512. The Korn shell is the preferred programming shell by many sh addicts,
  513. but it still suffers from inherent problems in the Bourne shell's design,
  514. such as parsing and evaluation horrors.  The Korn shell or its
  515. public-domain clones and supersets (like bash) aren't quite so ubiquitous
  516. as sh, so it probably wouldn't be wise to write a sharchive in them that
  517. you post to the net.  When 1003.2 becomes a real standard that companies
  518. are forced to adhere to, then we'll be in much better shape.  Until
  519. then, we'll be stuck with bug-incompatible versions of the sh lying about.
  520.  
  521. The Plan 9 shell, rc, is much cleaner in its parsing and evaluation; it is
  522. not widely available, so you'd be significantly sacrificing portability.
  523. No vendor is shipping it yet.
  524.  
  525. If you don't have to use a shell, but just want an interpreted language,
  526. many other free possibilities present themselves, like Perl, REXX, TCL,
  527. Scheme, or Python.  Of these, Perl is probably the most widely available
  528. on UNIX (and many other) systems and certainly comes with the most
  529. extensive UNIX interface.  Increasing numbers vendors ship Perl with 
  530. their standard systems.  (See the comp.lang.perl FAQ for a list.)
  531.  
  532. If you have a problem that would ordinarily use sed or awk or sh, but it
  533. exceeds their capabilities or must run a little faster, and you don't want
  534. to write the silly thing in C, then Perl may be for you.  You can get
  535. at networking functions, binary data, and most of the C library. There
  536. are also translators to turn your sed and awk scripts into Perl scripts,
  537. as well as a symbolic debugger.  Tchrist's personal rule of thumb is
  538. that if it's the size that fits in a Makefile, it gets written in the
  539. Bourne shell, but anything bigger gets written in Perl.
  540.  
  541. See the comp.lang.{perl,rexx,tcl} newsgroups for details about these
  542. languages (including FAQs), or David Muir Sharnoff's comparison of 
  543. freely available languages and tools in comp.lang.misc and news.answers.
  544. -- 
  545.     Tom Christiansen      tchrist@cs.colorado.edu       
  546.       "Will Hack Perl for Fine Food and Fun"
  547.     Boulder Colorado  303-444-3212
  548.  
  549.